# -*- coding: utf-8 -*-
"""
爬取哔哩哔哩追番列表

条件：pip install feapder

输入：UID,cookie,page
输出：CSV文件
"""
import csv

import feapder

writer = ''
rows = []
f = open('bili.csv', 'w', encoding='utf-8', newline="")


class AirSpiderTest(feapder.AirSpider):
    def start_callback(self):
        global writer
        writer = csv.writer(f)
        writer.writerow(['番剧名称', '地区', '上映时间', '总集数', 'b站短链', '评分', '评分人数', '播放量', '追番数'])
        print("爬虫开始")

    def end_callback(self):
        print("爬虫结束")
        writer.writerows(rows)
        f.close()

    def start_requests(self):
        # https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=0&pn=17&ps=15&vmid=37133980
        # https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=0&pn=17&ps=15&vmid=352627593
        for i in range(1, page + 1):
            yield feapder.Request(
                f"https://api.bilibili.com/x/space/bangumi/follow/list?type=1&follow_status=0&pn={i}&ps=15&vmid={uid}"
            )

    def download_midware(self, request):
        request.headers = {
            'user-agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
            'cookie': cookie
        }
        return request

    def parse(self, request, response):
        data_list = response.json.get('data').get('list')
        for item in data_list:
            title = item.get('title')
            total_count = item.get('total_count')
            follow = item.get('stat').get('follow')
            view = item.get('stat').get('view')
            score = item.get('rating').get('score') if item.get('rating', None) else '未开播'
            score_num = item.get('rating').get('count') if item.get('rating', None) else '未开播'
            area = item.get('areas')[0].get('name')
            pub_time = item.get('publish').get('release_date_show')
            short_url = item.get('short_url')
            # print(title, area, pub_time, total_count, short_url, score, score_num, view, follow)
            rows.append([title, area, pub_time, total_count, short_url, score, score_num, view, follow])


if __name__ == "__main__":
    cookie = input('输入cookie: ')
    page = int(input('追番列表页数: '))
    uid = input('输入你的UID: ')
    AirSpiderTest(thread_count=10).start()
